package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.innovation.chengzhangriji.ui.widget.ChangeAdapter;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

public class ChangePermissionActivity extends BaseActivity implements View.OnClickListener, CuteToolbar.OnClickCuteToolbarListener {

    private ChangeAdapter adapter;
    private int babyId;
    private ArrayList<BabyAllResponse> list;
    private String from = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String info = getIntent().getStringExtra("info");
        from = getIntent().getStringExtra("from");
        Log.e("结果info", info);
        BabyAllResponse[] responses = get(info, BabyAllResponse[].class);
        if (responses == null) {
            return;
        }

        list = new ArrayList<BabyAllResponse>();
        for (BabyAllResponse response : responses) {
            if (response.getAuth().getRole() == 2) {
                continue;
            }
            list.add(response);
        }
        setContentView(R.layout.activity_change_permission);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        Button btnChange = (Button) findViewById(R.id.btn_change);
        btnChange.setOnClickListener(this);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        adapter = new ChangeAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setList(list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change:
                LoginInfo login = Config.getLoginInfo(this);
                if (login == null) {
                    return;
                }
                String phone = login.getPhone();
                String token = login.getToken().getAccessToken();
                babyId = login.getBabyID();
                int userId = list.get(adapter.getPosition()).getUserId();
                Client.requestChangePermission(this, phone, token, babyId, userId, new ResponseHandler() {

                    @Override
                    public void onInnovationStart() {
                        super.onInnovationStart();
                        showProgressDialog(null, null);
                    }

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        updateAdmin();
                        updateDb();
//                        setResult(RESULT_OK);
                        if (TextUtils.isEmpty(from)) {
                            final LoginInfo loginInfo = Config.getLoginInfo(ChangePermissionActivity.this);
                            if (loginInfo == null) {
                                return;
                            }
                            final String phone = loginInfo.getPhone();
                            final String token = loginInfo.getToken().getAccessToken();
                            final String userID = loginInfo.getUserID();

                            Client.requestRemoveNote(ChangePermissionActivity.this, phone, token, babyId, new ResponseHandler() {

                                @Override
                                public void onInnovationStart() {
                                    showProgressDialog(null, null);
                                }

                                @Override
                                public void onInnovationSuccess(JsonElement value) {
                                    // 移除本地宝宝
                                    DatabaseManager.getInstance(ChangePermissionActivity.this).deleteBaby(babyId);
                                    // 发送删除通知
                                    // sendBroadcast(new Intent("delete"));

                                    dismissProgressDialog();
                                    Intent broad = new Intent("" + 100);
                                    sendBroadcast(broad);
                                    EventBus.getDefault().post(new BaseEvent(BaseEvent.TYPE_BABY_DELETED));

                                    finish();
                                }

                                @Override
                                public void onChZhRJFailure(String value) {
                                    dismissProgressDialog();
                                    tipShow(value);
                                }

                                @Override
                                public void onChZhRJTokenFailure(String value) {
                                    dismissProgressDialog();
                                    tipShow(value);
                                }

                            }, networkUnavailableSampleImpl());
                        } else if (from.equals("noticedetail")) {
//                            setResult(RESULT_OK);
//                            finish();
                            Intent intent = new Intent(ChangePermissionActivity.this, BabynoticeActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            startActivity(intent);
                            Intent broad = new Intent("" + 100);
                            sendBroadcast(broad);
                            finish();
                        }
//                        finish();
                    }

                    @Override
                    public void onInnovationFinish() {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onInnovationExceptionFinish() {
                        dismissProgressDialog();
                    }

                }, networkUnavailableSampleImpl());
                break;
        }
    }

    private void updateDb() {
        final LoginInfo loginInfo = Config.getLoginInfo(this);
        final String userId = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        final int babyId = loginInfo.getBabyID();
        Client.requestBabyAll(ChangePermissionActivity.this, phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                Parent[] parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(ChangePermissionActivity.this).deleteAllParents(babyId);
                DatabaseManager.getInstance(ChangePermissionActivity.this).insertOrReplaceInTxParent(parents);
                dismissProgressDialog();
//                Intent intent =  new Intent(ChangePermissionActivity.this,BabynoticeActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                startActivity(intent);
            }

        }, networkUnavailableSampleImpl());
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {

    }

    private void updateAdmin() {
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        String userId = login.getUserID();
        int babyId = login.getBabyID();
        DatabaseManager.getInstance(this).updateAdmin(userId, babyId);
    }
}
